package com.dianxin.smartpark.service.receiver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinatelecom.response.utils.StringUtils;
import com.dianxin.common.mqtt.listener.MsgReceiver;
import com.dianxin.common.mqtt.listener.MsgReceiverListener;
import com.dianxin.common.mqtt.service.MqttMsgSubscribe;
import com.dianxin.device.api.device.SmartParkDeviceRpcService;
import com.dianxin.device.api.device.dto.SmartDeviceDTO;
import com.dianxin.device.api.device.qo.SmartDeviceNoAclRpcQO;
import com.dianxin.smartpark.service.config.MqttReceiveType;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class MqttReceiverListener {

    @Resource
    private SmartParkDeviceRpcService smartParkDeviceRpcService;
    /**
     * 注册监听实现方法
     * 只需要让监听类被Spring管理即可，@EventListener注解会根据方法内配置的时间完成监听。
     * 接下来可启动项目来测试事件发布时是否被监听者所感知
     *
     * @param
     */
    @EventListener
    public void register(MsgReceiverListener msgReceiverListener) throws Exception {
        MsgReceiver msgReceiver = msgReceiverListener.getMsgReceiver();
        //设备监听
        if(msgReceiver.getTopic().contains(MqttReceiveType.CLIENTOPT.getOptCode())){
            JSONObject obj = JSON.parseObject(msgReceiver.getPayload());
            String clientid = obj.get("clientid").toString();
            SmartDeviceNoAclRpcQO qo = new SmartDeviceNoAclRpcQO();
            qo.setMacAddr(clientid);
            SmartDeviceDTO smartDeviceDTO = smartParkDeviceRpcService.getDeviceNoAcl(qo).getData();

            if(StringUtils.isNull(smartDeviceDTO)){
                return;
            }
            //不同业务处理
            if(msgReceiver.getTopic().contains(MqttReceiveType.ONLINE.getOptCode())){
                smartDeviceDTO.setIsOnline(1);
                smartParkDeviceRpcService.updateDevice(smartDeviceDTO);
            }

            if(msgReceiver.getTopic().contains(MqttReceiveType.DISONLINE.getOptCode())){
                smartDeviceDTO.setIsOnline(0);
                smartParkDeviceRpcService.updateDevice(smartDeviceDTO);
            }
        }

    }
}
